CODE 147. Evaluate Reverse Polish Notation

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/28/2013-11-28-CODE 147 Evaluate Reverse Polish Notation/

访问原文「CODE 147. Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /.
Each operand may be an integer or another expression.
Some examples:

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Solution {
public int evalRPN(String[] tokens) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
Stack<Integer> numbers = new Stack<Integer>();
for (String token : tokens) {
if (token.equals("+") || token.equals("-") || token.equals("*")
|| token.equals("/")) {
int number2 = numbers.pop();
int number1 = numbers.pop();
if (token.equals("+")) {
numbers.push(number1 + number2);
}
if (token.equals("-")) {
numbers.push(number1 - number2);
}
if (token.equals("*")) {
numbers.push(number1 * number2);
}
if (token.equals("/")) {
numbers.push(number1 / number2);
}
} else {
numbers.push(Integer.valueOf(token));
}
}
return numbers.pop();
}
Jerky Lu wechat
欢迎加入微信公众号